package com.jds.test.consoleim.client;

/**
 * Created by sunyuming on 18/8/17.
 */

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 主程序
 * @author shane
 *
 */
public class ClientMain {

    /**
     * 主函数
     * @param args
     */
    public static void main(String[] args) {

        try {
            DefaultThreadFactory defaultThreadFactory = new DefaultThreadFactory();
            ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), defaultThreadFactory);
            pool.execute(new ThreadNetty());
            pool.execute(new ThreadConsole());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger POOLNUMBER = new AtomicInteger(1);
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            namePrefix = "twslogserverpool-" + POOLNUMBER.getAndIncrement() + "-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
            if (t.isDaemon()) {
                t.setDaemon(false);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }

            t.setUncaughtExceptionHandler(new RewriteUncatchtExceptionHandler());
            return t;
        }
    }

    /*
    对ScheduledExecutorService无效
     */
    static class RewriteUncatchtExceptionHandler implements Thread.UncaughtExceptionHandler{
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
        }
    }

}
